//可以程序的任意位置调用getApp方法返回小程序的实例对象app
import { fetchStoredToken, removeStoredToken } from "./token";
const app = getApp();
function httpRequest(options) {
  //在发请求之前先获取保存的token
  const token = fetchStoredToken();
  if (token) {
    //如果有值的放在请求头中发送给服务器
    options.header = {
      ...options.header,
      Authorization: `Bearer ${token}`,
    };
  }
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      url: `${app.globalData.baseURL}${options.url}`,
      success: (response) => {
        if (response.statusCode >= 200 && response.statusCode < 300) {
          resolve(response.data);
          //如果返回401，说明本地存的token不合法,验证用户登录失败
        } else if (response.statusCode === 401) {
          removeStoredToken(); //移除本地保存的token
          //如果用户验证失败，则跳转到个人中心页进行登录
          wx.showModal({
            title: "认证失败",
            content: "请先登录",
            showCancel: false, //不能取消
            success() {
              //点击确定后跳转到个人中心页进行登录
              wx.navigateTo({
                url: "/pages/profile/profile",
              });
            },
          });
        }
      },
      fail: (error) => {
        console.log(error);
        reject(error);
      },
    });
  });
}
export function get(url, options = {}) {
  return httpRequest({
    url,
    ...options,
  });
}
export function post(url, options = {}) {
  return httpRequest({
    url,
    method: "POST",
    ...options,
  });
}
export default httpRequest;
